<script setup lang="ts">
import type { IProduct } from '@/api/interface/rescue/product/product'
import { onShow } from '@dcloudio/uni-app'
import { computed, onMounted, reactive, ref } from 'vue'
import MaterialsFilter from '@/components/rescue/filter/materials-filter.vue'
import ProductDetail from '@/components/rescue/ProductDetail.vue'
import ProductForm from '@/components/rescue/ProductForm.vue'
import ProductList from '@/components/rescue/ProductList.vue'

// 页面配置
defineOptions({
  name: 'MaterialsManage',
})

// 响应式数据
const filterParams = ref<Record<string, any>>({
  warehouseId: undefined,
  tagIds: [],
  searchType: 'name',
  searchText: '',
  productName: '',
  productNumber: '',
})

const productStats = reactive({
  total: 0,
  enabled: 0,
  disabled: 0,
  lowStock: 0,
})

const showDetailPopup = ref(false)
const showFormPopup = ref(false)
const selectedProductId = ref<number>()
const selectedProduct = ref<IProduct.Row>()

// 计算属性
const listQueryParams = computed(() => {
  const params: IProduct.Query = {
    page: 1,
    limit: 10,
  }

  // 应用筛选参数
  if (filterParams.value.warehouseId) {
    params.warehouseId = filterParams.value.warehouseId
  }

  if (filterParams.value.tagIds && filterParams.value.tagIds.length > 0) {
    params.tagIds = filterParams.value.tagIds
  }

  // 应用搜索参数
  if (filterParams.value.searchText) {
    if (filterParams.value.searchType === 'name') {
      params.name = filterParams.value.searchText
    } else if (filterParams.value.searchType === 'number') {
      params.productNumber = filterParams.value.searchText
    }
  }

  return params
})

// 方法
async function loadStats() {
  try {
    // 模拟统计数据，实际应该调用API
    productStats.total = 156
    productStats.enabled = 142
    productStats.disabled = 14
    productStats.lowStock = 8
  } catch (error) {
    console.error('加载统计信息失败:', error)
  }
}

function handleListRefresh() {
  console.log('列表刷新')
  loadStats()
}

function handleAddProduct() {
  selectedProduct.value = undefined
  showFormPopup.value = true
}

function handleViewDetail(product: IProduct.Row) {
  selectedProductId.value = product.id
  showDetailPopup.value = true
}

function handleProductClick(product: IProduct.Row) {
  handleViewDetail(product)
}

function handleEditProduct(product: IProduct.Row) {
  selectedProduct.value = product
  showFormPopup.value = true
}

function handleDetailEdit(product: IProduct.Row) {
  showDetailPopup.value = false
  setTimeout(() => {
    selectedProduct.value = product
    showFormPopup.value = true
  }, 300)
}

function handleDetailClose() {
  showDetailPopup.value = false
  selectedProductId.value = undefined
}

function handleFormSuccess() {
  showFormPopup.value = false
  selectedProduct.value = undefined

  // 重新加载数据
  handleListRefresh()
  loadStats()

  // 显示成功提示
  uni.showToast({
    title: selectedProduct.value ? '编辑成功' : '新增成功',
    icon: 'success',
    duration: 2000,
  })
}

function handleFormError(error: string) {
  uni.showToast({
    title: error || '操作失败',
    icon: 'error',
    duration: 2000,
  })
}

function handleFilterSearch() {
  // 筛选参数变化时，列表会自动刷新
  console.log('筛选搜索:', filterParams.value)
}

function handleFilterReset() {
  filterParams.value = {
    warehouseId: undefined,
    tagIds: [],
    searchType: 'name',
    searchText: '',
    productName: '',
    productNumber: '',
  }
}

function handleWarehouseChange(warehouseId: number | number[]) {
  console.log('仓库变化:', warehouseId)
}

function handleTagChange(tagIds: number | number[]) {
  console.log('标签变化:', tagIds)
}

function handleLoadMore() {
  console.log('加载更多')
}

// 生命周期
onMounted(() => {
  loadStats()
})

onShow(() => {
  // 页面显示时刷新数据
  loadStats()
})
</script>

<template>
  <view class="materials-manage">
    <!-- 主要内容 -->
    <view class="main-content">
      <!-- 筛选面板 -->
      <view class="filter-section">
        <MaterialsFilter
          v-model="filterParams"
          :show-warehouse="true"
          :show-tags="true"
          :show-search="true"
          :default-expanded="false"
          @search="handleFilterSearch"
          @reset="handleFilterReset"
          @warehouse-change="handleWarehouseChange"
          @tag-change="handleTagChange"
        />
      </view>

      <!-- 统计信息 -->
      <view class="stats-section">
        <view class="stats-card">
          <view class="stats-item">
            <text class="stats-label">总物资</text>
            <text class="stats-value">
              {{ productStats.total || 0 }}
            </text>
          </view>
          <view class="stats-item">
            <text class="stats-label">启用</text>
            <text class="stats-value enabled">
              {{ productStats.enabled || 0 }}
            </text>
          </view>
          <view class="stats-item">
            <text class="stats-label">禁用</text>
            <text class="stats-value disabled">
              {{ productStats.disabled || 0 }}
            </text>
          </view>
          <view class="stats-item">
            <text class="stats-label">低库存</text>
            <text class="stats-value warning">
              {{ productStats.lowStock || 0 }}
            </text>
          </view>
        </view>
      </view>

      <!-- 物资列表 -->
      <view class="list-section">
        <ProductList
          :query-params="listQueryParams"
          :auto-load="true"
          @product-click="handleProductClick"
          @view-detail="handleViewDetail"
          @edit-product="handleEditProduct"
          @refresh="handleListRefresh"
          @load-more="handleLoadMore"
        />
      </view>
    </view>

    <!-- 物资详情弹窗 -->
    <ProductDetail
      v-model="showDetailPopup"
      :product-id="selectedProductId"
      @edit="handleDetailEdit"
      @close="handleDetailClose"
    />

    <!-- 物资表单弹窗 -->
    <ProductForm
      v-model="showFormPopup"
      :product="selectedProduct"
      @success="handleFormSuccess"
      @error="handleFormError"
    />

    <!-- 浮动操作按钮 -->
    <view class="fab-container">
      <view type="primary" round class="fab-button" @click="handleAddProduct">
        <text>+</text>
        <wd-icon name="plus" size="24" />
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.materials-manage {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.navbar-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 0 16px;

  .navbar-title {
    font-size: 18px;
    font-weight: 600;
    color: #1d1d1f;
  }

  .navbar-actions {
    .add-btn {
      background: #007aff;
      border: none;
      border-radius: 8px;
      padding: 6px 12px;
      box-shadow: none;
      transition: all 0.2s ease;

      &:active {
        background: #0056cc;
        transform: scale(0.96);
      }

      :deep(.wd-button__text) {
        color: white;
        font-weight: 500;
        font-size: 15px;
      }

      :deep(.wd-icon) {
        margin-right: 6px;
      }
    }
  }
}

.main-content {
  padding: 16px;
  padding-top: 8px;
}

.filter-section {
  margin-bottom: 16px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.stats-section {
  margin-bottom: 16px;

  .stats-card {
    background: white;
    border-radius: 12px;
    padding: 16px;
    display: flex;
    justify-content: space-around;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);

    .stats-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      gap: 4px;

      .stats-label {
        font-size: 12px;
        color: #8e8e93;
        font-weight: 400;
      }

      .stats-value {
        font-size: 20px;
        font-weight: 600;
        color: #1d1d1f;

        &.enabled {
          color: #34c759;
        }

        &.disabled {
          color: #8e8e93;
        }

        &.warning {
          color: #ff9500;
        }
      }
    }
  }
}

.list-section {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  min-height: 400px;
}

.fab-container {
  position: fixed;
  right: 20px;
  bottom: 100px;
  z-index: 100;

  .fab-button {
    width: 40px;
    height: 40px;
    text-align: center;
    line-height: 40px;
    color: white;
    font-weight: 600;
    border-radius: 20px;
    background: #007aff;
    border: none;
    box-shadow: 0 4px 16px rgba(0, 122, 255, 0.3);
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s ease;

    &:active {
      background: #0056cc;
      transform: scale(0.92);
      box-shadow: 0 2px 8px rgba(0, 122, 255, 0.4);
    }

    :deep(.wd-button__text) {
      color: white;
    }
  }
}

/* 响应式设计 */
@media screen and (max-width: 750px) {
  .main-content {
    padding: 12px;
  }

  .stats-section .stats-card {
    padding: 12px;

    .stats-item .stats-value {
      font-size: 18px;
    }
  }

  .fab-container {
    right: 16px;
    bottom: 80px;

    .fab-button {
      width: 48px;
      height: 48px;
      border-radius: 24px;
    }
  }
}

/* 深色模式支持 */
@media (prefers-color-scheme: dark) {
  .materials-manage {
    background: linear-gradient(135deg, #1c1c1e 0%, #2c2c2e 100%);
  }

  .navbar-content .navbar-title {
    color: #f2f2f7;
  }

  .filter-section,
  .stats-section .stats-card,
  .list-section {
    background: #2c2c2e;
    color: #f2f2f7;
  }

  .stats-section .stats-card .stats-item .stats-value {
    color: #f2f2f7;

    &.enabled {
      color: #30d158;
    }

    &.disabled {
      color: #8e8e93;
    }

    &.warning {
      color: #ff9f0a;
    }
  }
}

/* 动画效果 */
.filter-section,
.stats-section .stats-card,
.list-section {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.fab-button {
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}

/* 加载状态 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;

  .loading-content {
    background: white;
    border-radius: 12px;
    padding: 24px;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);

    .loading-text {
      font-size: 14px;
      color: #8e8e93;
    }
  }
}
</style>
